package com.pubinfo.passbook.common.utils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Slf4j
public class EncryptUtil {
  
  private static final byte[] DESIV = new byte[]{0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef};// 向量
  private static final String deSkey = "CF_PASSWORD_JM";
  private static final String charset = "utf-8";
  
  /**
   * 初始化
   *
   * @param deSkey 密钥
   * @throws Exception
   */
  public EncryptUtil() throws Exception {
    
  }
  
  /**
   * 加密
   *
   * @param data
   * @return
   * @throws Exception
   * @author ershuai
   * @date 2017年4月19日 上午9:40:53
   */
  public static String encode(String data) {
    try {
      DESKeySpec keySpec = new DESKeySpec(EncryptUtil.deSkey.getBytes(EncryptUtil.charset));// 设置密钥参数
      AlgorithmParameterSpec iv = new IvParameterSpec(DESIV);// 设置向量
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
      Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象
      Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
      enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
      byte[] pasByte = enCipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
      BASE64Encoder base64Encoder = new BASE64Encoder();
      return base64Encoder.encode(pasByte);
    } catch (Exception e) {
      
    }
    return data;
  }
  
  /**
   * 解密
   *
   * @param data
   * @return
   * @throws Exception
   * @author ershuai
   * @date 2017年4月19日 上午9:41:01
   */
  public static String decode(String data) {
    try {
      DESKeySpec keySpec = new DESKeySpec(EncryptUtil.deSkey.getBytes(EncryptUtil.charset));// 设置密钥参数
      AlgorithmParameterSpec iv = new IvParameterSpec(DESIV);// 设置向量
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
      Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象
      Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
      deCipher.init(Cipher.DECRYPT_MODE, key, iv);
      BASE64Decoder base64Decoder = new BASE64Decoder();
      byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
      return new String(pasByte, StandardCharsets.UTF_8);
    } catch (Exception e) {
      
    }
    return data;
  }
  
}
